package com.jiyinit.web.core.run.controller;

import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.jiyinit.core.framework.base.entity.ResponseDto;
import com.jiyinit.core.framework.base.util.JsonEntityTransform;
import com.jiyinit.core.framework.base.util.LogUtil;
import com.jiyinit.web.core.business.entity.TabCoreUserEntity;
import com.jiyinit.web.core.business.service.UserServiceImpl;
import com.jiyinit.web.core.common.logic.ParamCheckLogic;
import com.jiyinit.web.core.common.logic.ValidateResult;
import com.jiyinit.web.core.mobile.controller.MfuntionController;

import com.jiyinit.web.core.run.dto.RunCountRequest;
import com.jiyinit.web.core.run.entity.TabRunCountEntity;
import com.jiyinit.web.core.run.service.RunCountServiceImpl;
import com.jiyinit.web.core.run.service.RunCountTotalServiceImpl;
import com.jiyinit.web.core.run.vo.RunCountVo;
import org.slf4j.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
@RequestMapping("mobile/runCount")
public class RunCountController {
    /**
     * 日志对象
     */
    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(MfuntionController.class);

    @Resource(name = "core.paramCheckLogic")
    private ParamCheckLogic paramCheckLogic;

    @Resource(name = "core.userServiceImpl")
    private UserServiceImpl userService;

    @Resource(name="run.runCountServiceImpl")
    private RunCountServiceImpl runCountService;

    @Resource(name="run.runCountTotalServiceImpl")
    private RunCountTotalServiceImpl runCountTotalService;


    /**
     * 步数统计上传
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/toAddRunCount")
    public ResponseEntity<ResponseDto> toAddRunCount(HttpServletRequest request) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException{
         RunCountRequest runCountRequest = getJsonToTaskRequest(request);

        ValidateResult<RunCountRequest> validateResult = paramCheckLogic.checkParamValidate(runCountRequest);
        if (!validateResult.isSuccess()) {
            return new ResponseEntity<>(validateResult.getDto(), HttpStatus.OK);
        }
        TabRunCountEntity runCountEntity = new TabRunCountEntity();
        Integer userId = runCountRequest.getUserId();
        String userName =" ";
        TabCoreUserEntity coreUserEntity=userService.getUserInfoByUserId(userId);
        if(null != coreUserEntity && !"".equals(coreUserEntity)){
            userName = coreUserEntity.getUserName();
        }

        String dateTime = getToday();
        String dataTimeToSs=getTodaySs();
        String stepNum = runCountRequest.getStepNum();
        String energy = runCountRequest.getEnergy();
        String distance =runCountRequest.getDistance();
        String device = runCountRequest.getDevice();
        int topOrgId= runCountRequest.getTopOrgId();

        if (null==device){
            device="";
        }
        String version =runCountRequest.getVersion();
        if(null == version){
            version = "";
        }
        runCountEntity.setUserId(userId);
        runCountEntity.setDateTime(dateTime);
        runCountEntity.setStepNum(stepNum);
        runCountEntity.setEnergy(energy);
        runCountEntity.setDistance(distance);
        runCountEntity.setBePressUp("0");
        runCountEntity.setDevice(device);
        runCountEntity.setVersion(version);
        runCountEntity.setTopOrgId(topOrgId);

        try{
            LOGGER.info("请求上传的用户名"+userId);
            runCountTotalService.add(runCountEntity);
            runCountEntity.setDateTime(dateTime);
            List<TabRunCountEntity> runCountCheck = runCountService.findCountById(runCountEntity);
            LOGGER.info("请求上传的用户工号"+userId+"请求上传的用户名"+userName+"请求上传的时间"+dataTimeToSs+"上传的总步数"+stepNum+"返回的数据总量"+runCountCheck.size());
            if(runCountCheck.size()==0){
                int res=runCountService.add(runCountEntity);
                LOGGER.info("返回的数据数量为0，去添加该用户的数据，添加结果"+res);
                if (res<0||res==0){
                    return new ResponseEntity<>(ResponseDto.responseFail("failed"), HttpStatus.OK);
                }
            }else if (runCountCheck.size()>0){
                int isSuc=runCountService.updateRunCount(runCountEntity);
                LOGGER.info("返回的数据数量大于1，去更新该用户的数据，更新结果"+isSuc);
                if (isSuc < 0 || isSuc ==0){
                    return new ResponseEntity<>(ResponseDto.responseFail("failed"), HttpStatus.OK);
                }
            }
        }catch(Exception e){
            return new ResponseEntity<>(ResponseDto.responseFail("failed"), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResponseDto.responseOK("success"), HttpStatus.OK);
    }


     /* *
     * 获取排名信息
     * @param request
     * @return
     * */
    @RequestMapping("/toGetRunList")
    @ResponseBody
    public ResponseEntity<ResponseDto> toGetRunList(HttpServletRequest request) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
        RunCountRequest runCountRequest = getJsonToTaskRequest(request);
        int topOrgId=runCountRequest.getTopOrgId();
        String dateTime=getToday();
        List<RunCountVo> list=runCountService.selectAllByDateTime(dateTime,topOrgId);
        return new ResponseEntity<>(ResponseDto.responseOK(list), HttpStatus.OK);
    }

    /**
     * 本周数据汇总
     * @param request
     * @return
     */
    @RequestMapping("/toGetRunCount")
    @ResponseBody
    public ResponseEntity<ResponseDto> toGetRunCount(HttpServletRequest request) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException{
        try{
            RunCountRequest runCountRequest = getJsonToTaskRequest(request);
            Integer selectId=runCountRequest.getSelectId();
            String endDate=getToday();
            String startDate=getStartDate(endDate);
            RunCountVo runCount=runCountService.selectOneByUserId(selectId,endDate);
            runCount.setTodayStepNum(runCount.getStepNum());
            List<TabRunCountEntity> weekList1 =runCountService.findWeekRunCountByUserId(selectId,startDate,endDate);
            if (weekList1.size()<7){
                int size=7-weekList1.size();
                for (int i=0;i<size;i++){
                    RunCountVo runCountVo=new RunCountVo();
                    runCountVo.setStepNum("0");
                    runCountVo.setEnergy("0");
                    runCountVo.setDistance("0");
                    runCountVo.setUserId(runCount.getUserId());
                    weekList1.add(weekList1.size(),runCountVo);
                }
            }
            List<TabRunCountEntity> weekList=new ArrayList<>();
            for (int i = 0; i < 7; i++) {
                weekList.add(i,weekList1.get(6-i));
            }
            runCount.setWeekList(weekList);
            return new ResponseEntity<>(ResponseDto.responseOK(runCount), HttpStatus.OK);
        }catch(Exception e){
            return new ResponseEntity<>(ResponseDto.responseFail("failed"), HttpStatus.OK);
        }
    }

    //格式转换
    private RunCountRequest getJsonToTaskRequest(HttpServletRequest request){
        String logJson = request.getParameter("request_json");
        LogUtil.info(LOGGER, "logJson:{}", logJson);
        RunCountRequest runCountRequest = (RunCountRequest) JsonEntityTransform.json2Object(logJson, RunCountRequest.class);
        return runCountRequest;
    }

    // 获得当前日
    public static String getToday(){
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String returnDate = sdf.format(date);
        return returnDate;
    }

    // 获得当前日小时
    public static String getTodaySs(){
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String returnDate = sdf.format(date);
        return returnDate;
    }

    //获得一周前日期
    public static String getStartDate(String endDate){
        Integer sd = Integer.parseInt(endDate)-6;
        String startDate=sd.toString();
        return startDate;
    }


}
